package com.bookstore.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bookstore.common.Result;
import com.bookstore.entity.Book;
import com.bookstore.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/books")
@Api(tags = "图书管理接口")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    @ApiOperation("分页查询图书列表")
    public Result<IPage<Book>> getBooks(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") int size) {
        return Result.success(bookService.getBooksByPage(page, size));
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询图书")
    public Result<Book> getBookById(
            @ApiParam("图书ID") @PathVariable Integer id) {
        return Result.success(bookService.getById(id));
    }

    @GetMapping("/category/{categoryId}")
    @ApiOperation("根据分类查询图书")
    public Result<IPage<Book>> getBooksByCategory(
            @ApiParam("分类ID") @PathVariable Integer categoryId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") int size) {
        return Result.success(bookService.getBooksByCategory(categoryId, page, size));
    }

    @GetMapping("/search")
    @ApiOperation("搜索图书")
    public Result<IPage<Book>> searchBooks(
            @ApiParam("搜索关键词") @RequestParam String keyword,
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") int size) {
        return Result.success(bookService.searchBooks(keyword, page, size));
    }

    @PostMapping
    @ApiOperation("添加图书")
    public Result<Boolean> addBook(@RequestBody Book book) {
        return Result.success(bookService.save(book));
    }

    @PutMapping("/{id}")
    @ApiOperation("更新图书信息")
    public Result<Boolean> updateBook(
            @ApiParam("图书ID") @PathVariable Integer id,
            @RequestBody Book book) {
        book.setBookId(id);
        return Result.success(bookService.updateById(book));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除图书")
    public Result<Boolean> deleteBook(
            @ApiParam("图书ID") @PathVariable Integer id) {
        return Result.success(bookService.removeById(id));
    }
} 